package org.csu.agrisupply.api.service.impl;

import org.csu.agrisupply.api.common.CommonResponse;
import org.csu.agrisupply.api.entity.Farmer;
import org.csu.agrisupply.api.entity.User;
import org.csu.agrisupply.api.persistence.FarmerMapper;
import org.csu.agrisupply.api.persistence.UserMapper;
import org.csu.agrisupply.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.List;

@Service("UserService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FarmerMapper farmerMapper;
    @Override
    public CommonResponse<List<User>> getUserList() {
        List<User> userList = userMapper.selectList(null);
        if(userList.isEmpty()){
            return CommonResponse.createForSuccessMessages("没有分类信息");
        }
        return CommonResponse.createForSuccess(userList);
    }

    @Override
    public CommonResponse<User> getUser(String userId) {
        User user = userMapper.selectById(userId);
        if(user == null)
        {
            return CommonResponse.createForSuccessMessages("没有该ID的user");
        }
        return  CommonResponse.createForSuccess(user);
    }
    @Override
    public CommonResponse<User> deleteUser(String userId){
        User user = userMapper.selectById(userId);
        if(user == null)
        {
            return CommonResponse.createForSuccessMessages("没有该ID的user");
        }
        userMapper.deleteById(userId);
        return CommonResponse.createForSuccessMessages("删除成功");
    }
    @Override
    public CommonResponse<User> updateUser(String userId,User newuser) {
        User user = userMapper.selectById(userId);
        if(user == null)
        {
            return CommonResponse.createForSuccessMessages("没有该ID的user");
        }
        user = newuser;
        userMapper.updateById(user);
        return CommonResponse.createForSuccess("修改成功",user);
    }

    @Override
    public CommonResponse<User> setRole(String userId, int role) {
        User user = userMapper.selectById(userId);
        if(user == null)
        {
            return CommonResponse.createForSuccessMessages("没有该ID的user");
        }
        user.setRole(role);
        userMapper.updateById(user);
        if(role == 2 || role == 1){
            if(farmerMapper.selectById(userId) == null){
                Farmer farmer = new Farmer();
                farmer.setUserId(userId);
                farmerMapper.insert(farmer);
            }
        }
        return CommonResponse.createForSuccess("设置成功",user);
    }
}
